import pygame
import random

# 初始化 Pygame
pygame.init()

# 游戏常量
WIDTH, HEIGHT = 800, 600
GRID_SIZE = 8
TILE_SIZE = 80
FPS = 60

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

# 初始化窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('消消乐小游戏')
clock = pygame.time.Clock()

# 定义方块类型和颜色
TILE_COLORS = [
    (255, 0, 0),    # 红色
    (0, 255, 0),    # 绿色
    (0, 0, 255),    # 蓝色
    (255, 255, 0),  # 黄色
    (255, 0, 255),  # 紫色
    (0, 255, 255)   # 青色
]

class Match3Game:
    def __init__(self):
        self.grid = [[random.randint(0, len(TILE_COLORS) - 1) for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)]
        self.selected_tile = None
        self.score = 0

    def draw_grid(self):
        for row in range(GRID_SIZE):
            for col in range(GRID_SIZE):
                tile_x = col * TILE_SIZE
                tile_y = row * TILE_SIZE
                color = TILE_COLORS[self.grid[row][col]]
                pygame.draw.rect(screen, color, (tile_x, tile_y, TILE_SIZE, TILE_SIZE))
                pygame.draw.rect(screen, BLACK, (tile_x, tile_y, TILE_SIZE, TILE_SIZE), 1)

    def handle_click(self, pos):
        col = pos[0] // TILE_SIZE
        row = pos[1] // TILE_SIZE
        
        if self.selected_tile is None:
            self.selected_tile = (row, col)
        else:
            s_row, s_col = self.selected_tile
            if abs(row - s_row) + abs(col - s_col) == 1:
                # 交换方块
                self.grid[row][col], self.grid[s_row][s_col] = self.grid[s_row][s_col], self.grid[row][col]
                if self.check_matches():
                    self.remove_matches()
                    self.fill_empty_spaces()
                else:
                    # 没有匹配，交换回来
                    self.grid[row][col], self.grid[s_row][s_col] = self.grid[s_row][s_col], self.grid[row][col]
            self.selected_tile = None

    def check_matches(self):
        for row in range(GRID_SIZE):
            for col in range(GRID_SIZE - 2):
                if self.grid[row][col] == self.grid[row][col + 1] == self.grid[row][col + 2]:
                    return True
        for col in range(GRID_SIZE):
            for row in range(GRID_SIZE - 2):
                if self.grid[row][col] == self.grid[row + 1][col] == self.grid[row + 2][col]:
                    return True
        return False

    def remove_matches(self):
        matches = []
        
        # 检查水平匹配
        for row in range(GRID_SIZE):
            for col in range(GRID_SIZE - 2):
                if self.grid[row][col] == self.grid[row][col + 1] == self.grid[row][col + 2]:
                    for i in range(3):
                        if (row, col + i) not in matches:
                            matches.append((row, col + i))
        
        # 检查垂直匹配
        for col in range(GRID_SIZE):
            for row in range(GRID_SIZE - 2):
                if self.grid[row][col] == self.grid[row + 1][col] == self.grid[row + 2][col]:
                    for i in range(3):
                        if (row + i, col) not in matches:
                            matches.append((row + i, col))
        
        # 移除匹配的方块
        for match in matches:
            self.grid[match[0]][match[1]] = -1
            self.score += 10

    def fill_empty_spaces(self):
        for col in range(GRID_SIZE):
            # 将方块向下移动
            new_col = []
            for row in range(GRID_SIZE - 1, -1, -1):
                if self.grid[row][col] != -1:
                    new_col.append(self.grid[row][col])
            
            # 填充新的方块
            while len(new_col) < GRID_SIZE:
                new_col.append(random.randint(0, len(TILE_COLORS) - 1))
            
            # 更新网格
            for row in range(GRID_SIZE):
                self.grid[GRID_SIZE - 1 - row][col] = new_col[row]

        # 检查是否还有匹配
        if self.check_matches():
            self.remove_matches()
            self.fill_empty_spaces()

    def draw_score(self):
        font = pygame.font.Font(None, 36)
        text = font.render(f'分数: {self.score}', True, BLACK)
        screen.blit(text, (10, 10))

def main():
    game = Match3Game()
    running = True
    
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                game.handle_click(pygame.mouse.get_pos())

        screen.fill(WHITE)
        game.draw_grid()
        game.draw_score()
        
        pygame.display.flip()
        clock.tick(FPS)

    pygame.quit()

if __name__ == '__main__':
    main()